package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.exception.CustException;
import com.heima.feigns.UserFeign;
import com.heima.model.common.constants.user.UserRelationConstants;
import com.heima.model.common.dtos.PageRequestDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.wemedia.pojos.WmNewsStatistics;
import com.heima.model.wemedia.vos.FansListVo;
import com.heima.model.wemedia.vos.WmFansVos;
import com.heima.wemedia.service.FansPortraitService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class FansPortraitServiceImpl implements FansPortraitService {
    @Autowired
    UserFeign userFeign;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Override
    public ResponseResult fansPortrait() {
        //没有参数要检查
        //远程查询
        ResponseResult<List<ApUser>> allApUser = userFeign.findAllApUser();
        if (!allApUser.checkCode()){
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
        }
        List<ApUser> data = allApUser.getData();
        if (data==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        //过滤留下是自己粉丝的
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();

        List<ApUser> apUsers = data.stream().filter(apUser -> {
            Integer apUserId = apUser.getId();
            Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FANS_LIST + userId, apUserId);
            return score != null;
        }).collect(Collectors.toList());
        //从中获取数据
        List<WmFansVos> wmFansVosList = new ArrayList<>();
       //首先根据性别分类
        Map<Boolean, List<ApUser>> sexList = apUsers.stream().collect(Collectors.groupingBy(ApUser::getSex));
        int maleSize = sexList.get(true).size();//男的数量
        int femaleSize = sexList.get(false).size();//女的数量
        WmFansVos sexWmFansVosM = new WmFansVos();
        sexWmFansVosM.setId(1);//不重要的数据
        sexWmFansVosM.setName("sex:male");
        sexWmFansVosM.setValue(String.valueOf(maleSize));
        sexWmFansVosM.setUser_id(1);
        sexWmFansVosM.setCreated_time("写死");
        WmFansVos sexWmFansVosFM = new WmFansVos();
        sexWmFansVosFM.setId(1);//不重要的数据
        sexWmFansVosFM.setName("sex:female");
        sexWmFansVosFM.setValue(String.valueOf(femaleSize));
        sexWmFansVosFM.setUser_id(1);
        sexWmFansVosFM.setCreated_time("写死");
        wmFansVosList.add(sexWmFansVosM);
        wmFansVosList.add(sexWmFansVosFM);
        //再根据年龄分类
        List<WmFansVos> ageLeve = getAgeLevel(apUsers);
        wmFansVosList.addAll(ageLeve);
        //再根据阅读量分类
        SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date time = sim.parse(sim.format(new Date()));
            List<WmNewsStatistics> wmNewsStatistics = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId).and("creatTime").lte(time)).with(Sort.by(Sort.Direction.DESC, "creatTime")).limit(7), WmNewsStatistics.class);
            for (WmNewsStatistics wmNewsStatistic : wmNewsStatistics) {
                WmFansVos wmFansVos = new WmFansVos();
                wmFansVos.setCreated_time("写死");
                wmFansVos.setName("read:"+sim.format(wmNewsStatistic.getCreatTime()));
                wmFansVos.setValue(String.valueOf(wmNewsStatistic.getReadCount()));
                wmFansVos.setId(1);
                wmFansVos.setUser_id(1);
                wmFansVosList.add(wmFansVos);
            }

        } catch (ParseException parseException) {
            parseException.printStackTrace();
        }
        //写死一个操作系统数据
        WmFansVos wmFansVosIOS = new WmFansVos();
        wmFansVosIOS.setUser_id(1);
        wmFansVosIOS.setId(1);
        wmFansVosIOS.setCreated_time("写死");
        wmFansVosIOS.setValue("1");
        wmFansVosIOS.setName("mobile:ios");
        WmFansVos wmFansVosADD = new WmFansVos();
        wmFansVosADD.setUser_id(1);
        wmFansVosADD.setId(1);
        wmFansVosADD.setCreated_time("写死");
        wmFansVosADD.setValue("99");
        wmFansVosADD.setName("mobile:andorid");
        wmFansVosList.add(wmFansVosADD);
        wmFansVosList.add(wmFansVosIOS);
        //返回数据
        return ResponseResult.okResult(wmFansVosList);
    }

    @Override
    public ResponseResult list(PageRequestDTO dto) {
        //检查参数  设置默认值
        dto.checkParam();
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        Integer userId = user.getId();
        //分页查询
        Set<String> rangefans = redisTemplate.opsForZSet().range(UserRelationConstants.FANS_LIST + userId, (long) (dto.getPage() - 1) *dto.getSize(),(long) (dto.getPage() - 1) *dto.getSize()+dto.getSize()-1);
        if (rangefans==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
//        List<ApUser> apUsers = range.stream().map(s -> {
//            //根据远程接口查询ApUser信息
//            ResponseResult<ApUser> result = userFeign.findUserById(Integer.valueOf(s));
//            if (!result.checkCode()) {
//                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
//            }
//            return result.getData();
//        }).collect(Collectors.toList());
        //再查询自己关注的
        Set<String> rangeFollow = redisTemplate.opsForZSet().range(UserRelationConstants.FOLLOW_LIST + userId, 0, -1);
        if (rangeFollow==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"赶紧去关注一下漂亮的女主播吧");
        }
        //把rangeFollow和rangefans求并集得到的就是互关
        Set<String> youAndMe = new HashSet<String>(rangefans);
        youAndMe.retainAll(rangeFollow);
        //获得两者差集
        Set<String> fans= new HashSet<String>(rangefans);
        fans.removeAll(rangeFollow);
        Set<String> set = new HashSet<>();
        set.addAll(fans);
        set.addAll(youAndMe);
        int size = rangeFollow.size()-fans.size();
        //两者加起来得到长度为10的集合
        List<ApUser> apUsers = set.stream().map(s -> {
            //根据远程接口查ApUser
            ResponseResult<ApUser> result = userFeign.findUserById(Integer.valueOf(s));
            if (!result.checkCode()) {
                CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR);
            }
            return result.getData();
        }).collect(Collectors.toList());
        List<FansListVo> result = new ArrayList<>();
        for (ApUser apUser : apUsers) {
            int i =1;
            boolean isFollow= i <= size;
            FansListVo fansListVo = new FansListVo();
            fansListVo.setId(i++);
            fansListVo.setFans_name(apUser.getName());
            fansListVo.setFans_id(apUser.getId());
            fansListVo.set_follow(isFollow);
            fansListVo.setPhoto(apUser.getImage());
            result.add(fansListVo);
        }
        return ResponseResult.okResult(result);
    }

    private List<WmFansVos> getAgeLevel(List<ApUser> apUsers) {
        int level1=0;
        int level2=0;
        int level3=0;
        int level4=0;
        for (ApUser apUser : apUsers) {
            Integer age = apUser.getAge();
            if (age<=20&&age>0){
                level1+=1;
            }else if(age>20&&age<=30){
                level2+=1;
            }else if (age>30&&age<=50){
                level3+=1;
            }else {
                level4+=1;
            }
        }
        ArrayList<WmFansVos> wmFansVos = new ArrayList<>();
        //
        if (level1!=0){
            WmFansVos wmFansVos1 = new WmFansVos();
            wmFansVos1.setId(1);
            wmFansVos1.setName("age:0-20");
            wmFansVos1.setUser_id(1);
            wmFansVos1.setValue(String.valueOf(level1));
            wmFansVos1.setCreated_time("写死");
            wmFansVos.add(wmFansVos1);
        }
        if (level2!=0){
            WmFansVos wmFansVos1 = new WmFansVos();
            wmFansVos1.setId(1);
            wmFansVos1.setName("age:20-30");
            wmFansVos1.setUser_id(1);
            wmFansVos1.setValue(String.valueOf(level2));
            wmFansVos1.setCreated_time("写死");
            wmFansVos.add(wmFansVos1);

        }
        if (level3!=0){
            WmFansVos wmFansVos1 = new WmFansVos();
            wmFansVos1.setId(1);
            wmFansVos1.setName("age:30-50");
            wmFansVos1.setUser_id(1);
            wmFansVos1.setValue(String.valueOf(level3));
            wmFansVos1.setCreated_time("写死");
            wmFansVos.add(wmFansVos1);

        }
        if (level4!=0){
            WmFansVos wmFansVos1 = new WmFansVos();
            wmFansVos1.setId(1);
            wmFansVos1.setName("age:>50");
            wmFansVos1.setUser_id(1);
            wmFansVos1.setValue(String.valueOf(level4));
            wmFansVos1.setCreated_time("写死");
            wmFansVos.add(wmFansVos1);

        }
        return wmFansVos;
    }
}
